<?php

namespace app\service;

use app\models\AccountMoney;
use app\models\Customer;
use app\models\Income;
use app\models\IncomeProperty;
use app\models\IncomeType;
use app\models\Staff;

class IncomeService
{
    /**
     * 添加一条拆分记录
     * @param array $array
     * @return bool
     */
    public function insert_split($array)
    {
        $model        = new Income();
        $array['pid'] = $array['id'];
        $lastInsertId = $model->copy_record($array['id']);
        unset($array['id']);
        return $model->update_record($array, $lastInsertId);
    }

    /**
     * income列表
     * @param int $p 分页page
     * @param int $s 分页size
     * @param array $where 分页查询条件
     * @return array
     */
    public function incomeList($p, $s, $where = [])
    {
        $db       = new Income();
        $caculate = $db->get_caculate_data($where);
        $size     = $db->get_income_size($where);
        $datalist = $db->all($where, ($p - 1) * $s, $s, ['date' => SORT_DESC, 'pid' => SORT_DESC]);
        $chart    = $db->chartData($where);
        //收入来源
        $model        = new IncomeType();
        $incomeType   = $model->all();
        $model        = new IncomeProperty();
        $propertyList = $model->all();
        $accountMoney = new AccountMoney();
        $accountList  = $accountMoney->all();
        $title        = [];
        foreach ($chart as $k => $v) {
            foreach ($propertyList as $v2) {
                if ($v['property_p'] == $v2['id']) {
                    $title[]           = $v2['name'];
                    $chart[$k]['name'] = $v2['name'];
                }
            }
        }

        //检测客户编号和名称是否一致
        $datalist = $this->validateCustomer($datalist);

        //业务员列表
        $staffModel = new Staff();
        $staffList  = $staffModel->get_all_saleman();

        $data               = [];
        $data['list']       = $datalist;
        $data['size']       = $size;
        $data['caculate']   = $caculate;
        $data['incomeType'] = $incomeType;
        $data['property']   = $propertyList;
        $data['staff']      = $staffList;
        $data['title']      = $title;
        $data['chart']      = $chart;
        $data['account']    = $accountList;
        return $data;
    }

    /**
     * @return mixed
     */
    public function incomeBase()
    {
        $model = new IncomeType();
        //收款方式
        $incomeType = $model->all();

        $model = new IncomeProperty();
        //收款类型
        $propertyList = $model->all();
        $accountMoney = new AccountMoney();
        $accountList  = $accountMoney->all();
        $tmp          = [];
        foreach ($accountList as $v) {
            $tmp[] = $v;
        }
        $accountList = $tmp;
        //业务员列表
        $staffModel = new Staff();
        $staffList  = $staffModel->get_all_saleman();
        foreach ($incomeType as $k => $v) {
            $incomeType[$k]['value'] = $v['name'];
        }
        foreach ($propertyList as $k => $v) {
            $propertyList[$k]['value'] = $v['name'];
        }
        foreach ($staffList as $k => $v) {
            $staffList[$k]['id']    = $v['job_number'];
            $staffList[$k]['value'] = $v['name'];
        }
        $data['incomeType'] = $incomeType;
        $data['property']   = $propertyList;
        $data['staff']      = $staffList;
        $data['account']    = $accountList;
        return $data;
    }

    public function apiList($p, $s, $where = [])
    {
        $db   = new Income();
        $list = $db->all($where, ($p - 1) * $s, $s, ['date' => SORT_DESC, 'pid' => SORT_DESC, 'id' => SORT_ASC]);
        //校验客户名称
        $list = $this->validateCustomer($list);
        $size = $db->get_income_size($where);
        return ['list' => $list, 'total' => $size];
    }

    /**下载excel
     * @param $where
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    function list($where) {
        $model        = new Income();
        $datalist     = $model->all($where, '', '', ['date' => SORT_DESC, 'pid' => SORT_DESC]);
        $model        = new IncomeType();
        $incomeType   = $model->all();
        $model        = new IncomeProperty();
        $propertyList = $model->all();
        $model        = new Staff();
        $staffList    = $model->get_all_saleman();
        $excel        = new \PHPExcel();
        $excel->setActiveSheetIndex(0)
            ->setCellValue('A1', '日期')
            ->setCellValue('B1', '是否拆分')
            ->setCellValue('C1', '性质')
            ->setCellValue('D1', '交易对手方名称')
            ->setCellValue('E1', '编号')
            ->setCellValue('F1', '客户名称')
            ->setCellValue('G1', '国家')
            ->setCellValue('H1', '业务员')
            ->setCellValue('I1', '类型')
            ->setCellValue('J1', '币总')
            ->setCellValue('K1', 'invoice编号')
            ->setCellValue('L1', '收入')
            ->setCellValue('M1', '支出')
            ->setCellValue('N1', '费用')
            ->setCellValue('O1', '净额')
            ->setCellValue('P1', '备注')
            ->setCellValue('Q1', '支付来源');
        foreach ($datalist as $k => $v) {
            $num = $k + 2;

            //Excel的第A列，uid是你查出数组的键值，下面以此类推
            $excel->setActiveSheetIndex(0)->setCellValue('A' . $num, $v['date']);
            $excel->setActiveSheetIndex(0)->setCellValue('B' . $num, (int) $v['pid'] != $v['id'] ? '拆分项' : '');
            foreach ($propertyList as $v2) {
                if ($v2['id'] == $v['property_p']) {
                    $tmp = $v2['name'];
                    break;
                }
            }
            $excel->setActiveSheetIndex(0)->setCellValue('C' . $num, $tmp);
            $excel->setActiveSheetIndex(0)->setCellValue('D' . $num, $v['name']);
            $excel->setActiveSheetIndex(0)->setCellValue('E' . $num, $v['number']);
            $excel->setActiveSheetIndex(0)->setCellValue('F' . $num, $v['customer_name']);
            $excel->setActiveSheetIndex(0)->setCellValue('G' . $num, $v['country']);
            $name = '';
            foreach ($staffList as $v2) {
                if ($v['service_name'] == $v2['job_number']) {
                    $name = $v2['name'];
                    break;
                }
            }
            $excel->setActiveSheetIndex(0)->setCellValue('H' . $num, $name);
            $tmp = '';
            if ($v['pay_type'] == 1) {
                $tmp = '支出';
            } else if ($v['pay_type'] == 2) {
                $tmp = '退款';
            } else if ($v['pay_type'] == 3) {
                $tmp = '收款';
            }
            $excel->setActiveSheetIndex(0)->setCellValue('I' . $num, $tmp);
            $excel->setActiveSheetIndex(0)->setCellValue('J' . $num, $v['money_type']);
            $excel->setActiveSheetIndex(0)->setCellValue('K' . $num, $v['invocie_num']);
            $excel->setActiveSheetIndex(0)->setCellValue('L' . $num, $v['in_come']);
            $excel->setActiveSheetIndex(0)->setCellValue('M' . $num, $v['total_fee']);
            $excel->setActiveSheetIndex(0)->setCellValue('N' . $num, $v['fee']);
            $excel->setActiveSheetIndex(0)->setCellValue('O' . $num, $v['in_come'] + $v['total_fee'] + $v['fee']);
            $excel->setActiveSheetIndex(0)->setCellValue('P' . $num, $v['remark']);
            $tmp = "";
            foreach ($incomeType as $v2) {
                if ($v2['id'] == $v['pay_from']) {
                    $tmp = $v2['name'];
                    break;
                }
            }
            $excel->setActiveSheetIndex(0)->setCellValue('Q' . $num, $tmp);

        }

        $name = '收入';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $objWriter->save('php://output');
    }

    /**检测客户编号和名称是否一致
     * @param $datalist
     */
    public function validateCustomer($datalist)
    {

        $customerArr = [];
        foreach ($datalist as $v) {
            $customerArr[] = $v['number'];
        }
        $model = new Customer();
        $list  = $model->getCustomerByNum($customerArr);
        foreach ($datalist as $k => $v) {
            if (isset($list[$v['number']])) {
                if ($v['customer_name'] != $list[$v['number']]) {
                    $datalist[$k]['same'] = false;
                } else {
                    $datalist[$k]['same'] = true;
                }
            } else {
                $datalist[$k]['same'] = false;
            }
        }
        return $datalist;
    }

}
